package com.github.fishlikewater.httppierce.exception;


import io.github.fishlikewater.raiden.core.enums.StatusEnum;
import io.github.fishlikewater.raiden.core.model.Result;
import jakarta.security.auth.message.AuthException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 统一处理异常
 *
 * @author fish
 */
@ConditionalOnProperty(prefix = "http.pierce", name = "boot-type", havingValue = "${http.pierce.boot-type:client}")
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    public static final String ERROR_TEXT = "异常信息";

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Result<String> processMethod(MissingServletRequestParameterException ex) {
        log.error(ERROR_TEXT + "：", ex);
        return Result.of(StatusEnum.UNAUTHORIZED_INVALID_MISSING_REQUIRED_PARAMETER.code(), "参数[" + ex.getParameterName() + "]不能为空");
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result<String> processMethod(HttpMessageNotReadableException ex) {
        log.error(ERROR_TEXT + "：", ex);
        return Result.of(StatusEnum.UNAUTHORIZED_INVALID_MISSING_REQUIRED_PARAMETER.code(), "请求参数不合法");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> processMethod(MethodArgumentNotValidException ex) {
        log.error(ERROR_TEXT + "：", ex);
        return Result.of(StatusEnum.BAD_REQUEST, ex.getBindingResult().getAllErrors().getFirst().getDefaultMessage());
    }

    @ExceptionHandler(value = {AuthException.class, BindException.class, ConstraintViolationException.class})
    public Result<Object> processMethod(AuthException ex) {
        log.error(ERROR_TEXT + "：", ex);
        return Result.of(StatusEnum.BAD_REQUEST, ex.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Result<Object> processMethod(Exception ex) {
        log.error(ERROR_TEXT + "：", ex);
        return Result.of(StatusEnum.BAD_REQUEST, "服务访问异常");
    }
}

